package gui.panels;

import com.google.common.eventbus.Subscribe;
import contracts.requests.GetOnlineUserCountRequest;
import contracts.requests.MessageRequest;
import contracts.responses.*;
import eventbus.PageEventBus;
import eventbus.events.UpdatePanelEvent;
import gui.BasePanel;
import network.websocket.WSClient;
import network.websocket.WSClientSender;
import state.SessionState;
import util.DialogHelper;
import util.StringValidator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Timestamp;

public class ChatPanel extends BasePanel {

    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    JTextField msgInput = new JTextField();
    JButton sendButton = new JButton("发送");
    JLabel onlineUserCount = new JLabel();
    JButton offlineButton = new JButton("退出聊天室");

    public ChatPanel() {
        offlineButton.setForeground(Color.red);
        offlineButton.setBounds(650, 10, 100, 30);
        scrollPane.setBounds(100, 50, 600, 250);
        //分别设置水平和垂直滚动条总是出现
        scrollPane.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        msgInput.setBounds(150, 320, 400, 35);
        sendButton.setBounds(550, 320, 100, 35);
        onlineUserCount.setBounds(660, 350, 140, 35);
        this.add(offlineButton);
        this.add(scrollPane);
        this.add(msgInput);
        this.add(sendButton);
        this.add(onlineUserCount);
        sendButton.addActionListener(e -> {
            sendMessage();
        });
        msgInput.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    sendMessage();
                }
            }
        });
        offlineButton.addActionListener(e -> {
            SessionState.Instance.setLoginSuccess(false);
            DialogHelper.showSuccessDialog("您已经成功退出聊天室");
            WSClient.Instance.closeConnect();
            PageEventBus.publish(UpdatePanelEvent.create(LoginPanel.class));
        });
        WSClientSender.send(new GetOnlineUserCountRequest());
    }

    void sendMessage() {
        String msg = msgInput.getText().trim();
        if (!StringValidator.isBlank(msg)) {
            MessageRequest request = new MessageRequest(msg);
            WSClientSender.send(request);
            msgInput.setText("");
        }
    }

    @Subscribe
    public void messageResponseHandle(MessageResponse m) {
        //消息格式化后追加到textArea中
        Timestamp now = new Timestamp(System.currentTimeMillis());
        String formatMsg = String.format("%s\n%s说:%s\n\n", now, m.nickname, m.content);
        textArea.append(formatMsg);
        //将光标移动到尾部来达成滚动条到底部的效果
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Subscribe
    public void forcedOfflineResponseHandle(ForcedOfflineResponse response) {
        PageEventBus.publish(UpdatePanelEvent.create(LoginPanel.class));
        DialogHelper.showWaringDialog(response.message);
        SessionState.Instance.setLoginSuccess(false);
        WSClient.Instance.closeConnect();
    }

    @Subscribe
    public void tabooResponseHandle(TabooResponse response) {
        DialogHelper.showWaringDialog(response.message);
    }

    @Subscribe
    public void onlineCountResponseHandle(OnlineUserCountResponse response) {
        onlineUserCount.setText("在线用户: " + response.count + "人");
    }

    @Subscribe
    public void loginByTokenResponseHandle(LoginByTokenResponse response) {
        if (response.success) {
            SessionState.Instance.setToken(response.token);
            SessionState.Instance.setConnId(response.connectId);
        } else {
            DialogHelper.showWaringDialog("身份信息失效,请重新登录");
            PageEventBus.publish(UpdatePanelEvent.create(LoginPanel.class));
        }
    }

    @Override
    public BasePanel clearAllInput() {
        textArea.setText("");
//        onlineUserCount.setText("在线用户: ");
        return this;
    }
}
